//
//  HCComposeView.swift
//  Hweibome
//
//  Created by apple on 15/12/14.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit
import pop

class HCComposeView: UIView {
    
    var target : UIViewController?
    
    private lazy var buttons: [HCComposeMenuButton] = [HCComposeMenuButton]()
    
    private var composeButtonInfos: [HCComposeButtonInfo]?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        width = SCREENW
        height = SCREENH
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
    //    backgroundColor = RandomColor()
        //add subview
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        sloganImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        addChildButton()
       
    }
    
    private func addChildButton(){
        let childW:CGFloat = 80
        let childH:CGFloat = 110
        
        let childMargin: CGFloat = (SCREENW - 3*childW) / 4
        
      
       composeButtonInfos = getComposeButtonInfos()
        for (i,value) in composeButtonInfos!.enumerate(){
            let button = HCComposeMenuButton()
            let icon = value.icon!
            let title = value.title!
            button.setImage(UIImage(named:icon),forState:.Normal)
            button.setTitle(title,forState: .Normal)
            button.tag = i
            button.size = CGSize(width: childW , height: childH)
            button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            let col = i % 3
            let row = i / 3
            
            button.x = CGFloat(col + 1 )*childMargin + CGFloat(col)*childW
            button.y = CGFloat(row)*(childMargin + childH) + SCREENH
            addSubview(button)
            buttons.append(button)
         }
 }
    
    @objc private func composeButtonClick(button:UIButton){
        UIView.animateWithDuration(0.25 , animations: { () -> Void in
            for value in self.buttons {
                value.alpha = 0.2
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.5, 0.5)
                }
            }
            }) {
                (_) -> Void in
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    for value in self.buttons {
//                        value.alpha = 1
//                        value.transform = CGAffineTransformIdentity
//                    }
//                })
                
                let info = self.composeButtonInfos![button.tag]
                if let name = info.classname {
                    let cls = NSClassFromString(name) as? UIViewController.Type
                    let result = cls?.init()
                    self.target?.presentViewController(HCNavigationController(rootViewController: result!), animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                    })
                }
        }
    }
    
    private func getComposeButtonInfos() -> [HCComposeButtonInfo] {
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let composeButtonInfos = NSArray(contentsOfFile: file)!
        var result = [HCComposeButtonInfo]()
        
        for value in composeButtonInfos {
            result.append(HCComposeButtonInfo(dict: value as! [String:AnyObject]))
        }
        return result
    }
    
    func show(target: UIViewController?){
    
//        let window = UIApplication.sharedApplication().windows.last
//        window?.addSubview(self)
        self.target = target
        target?.view.addSubview(self)
        
        for (i , value) in buttons.enumerate() {
            anim(value, index: i)
        }
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        removeFromSuperview()
    }
    
    
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.screentShot().applyLightEffect())
    
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
    private func anim (button:UIButton,isUp:Bool = true,index:Int) {
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        let y : CGFloat = isUp ? button.center.y - 350 : button.center.y + 350
        anim.toValue = NSValue(CGPoint:CGPoint(x : button.center.x , y : y))
        anim.springBounciness = 8
        anim.springSpeed = 10
        anim.beginTime = CACurrentMediaTime() + Double(index)*0.025
        button.pop_addAnimation(anim,forKey:nil)

    }
    
    
    


}
